package com.yz.kafka.consumers;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * 独立的消费者
 *
 * @author yuanzheng
 * @since 2021/3/7
 */
public class SimpleConsumerStandAlone {
    public static void main(String[] args) {
        String topic = "Hello-Kafka";
        String group = "group1";
        Properties props = new Properties();
        props.put("bootstrap.servers", "hadoop001:9092");
        /*指定分组 ID*/
        props.put("group.id", group);
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        /*订阅主题 (s)*/
        consumer.subscribe(Collections.singletonList(topic));
        try {
            List<TopicPartition> partitions = new ArrayList<>();
            List<PartitionInfo> partitionInfos = consumer.partitionsFor(topic);
            /*可以指定读取哪些分区 如这里假设只读取主题的 0 分区*/
            for (PartitionInfo partition : partitionInfos) {
                if (partition.partition() == 0) {
                    partitions.add(new TopicPartition(partition.topic(), partition.partition()));
                }
            }
            // 为消费者指定分区
            consumer.assign(partitions);

            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.of(100, ChronoUnit.MILLIS));
                for (ConsumerRecord<String, String> record : records) {
                    System.out.printf("partition = %s, key = %d, value = %s\n",
                            record.partition(), record.key(), record.value());
                }
                consumer.commitSync();
            }
        } finally {
            consumer.close();
        }
    }
}
